package com.bp.api.system;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.bp.vo.UserMessageVO;
import com.common.enums.CommonCode;
import com.common.enums.SystemStatusEnum;
import com.common.model.PageModel;
import com.idp.biz.bpuser.entity.BpUser;
import com.idp.biz.bpuser.service.BpUserService;
import com.idp.biz.bpusermessage.entity.BpUserMessage;
import com.idp.biz.bpusermessage.service.BpUserMessageService;

/**
 * 用户消息
 */
@RestController
@RequestMapping(value = "/api/message/", method = RequestMethod.POST)
public class MessageController {
    private static Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private BpUserService userService;
    @Autowired
    private BpUserMessageService messageService;

    @Autowired
    private StringRedisTemplate redis;

    /**
     * 我的消息列表
     */
    @CrossOrigin
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        PageModel<BpUserMessage> page = new PageModel<>();
        try {
        	Integer draw = StringUtils.isNotEmpty(request.getParameter("draw")) ? Integer.valueOf(request.getParameter("draw")) : 0 ;//页号
			Integer length = StringUtils.isNotEmpty(request.getParameter("length")) ? Integer.valueOf(request.getParameter("length")) : 0 ;//每页条数
			//Integer recordsFiltered = StringUtils.isNotEmpty(request.getParameter("recordsFiltered")) ? Integer.valueOf(request.getParameter("recordsFiltered")) : 0 ;//过滤后总条数
			Integer recordsTotal = StringUtils.isNotEmpty(request.getParameter("recordsTotal")) ? Integer.valueOf(request.getParameter("recordsTotal")) : 0 ;//总条数
			Integer start = StringUtils.isNotEmpty(request.getParameter("start")) ? Integer.valueOf(request.getParameter("start")) : 0 ;//起始条数
			page.setDraw(draw);
			page.setLength(length);
			// page.setRecordsFiltered(recordsFiltered);
			page.setRecordsTotal(recordsTotal);
			page.setStart(start);
        	
            String token = request.getParameter("token");
            if (StringUtils.isEmpty(token)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            String isLogin = redis.opsForValue().get(token);
            if (StringUtils.isEmpty(isLogin)) {
                json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);
            if (user == null) {
                json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
                json.put("message", SystemStatusEnum.USER_IS_NULL.getName());
                return json.toJSONString();
            }
            List<UserMessageVO> dataList = new ArrayList<>();
            BpUserMessage message = new BpUserMessage();
            message.setUserId(user.getId());
            message.setSymbol(CommonCode.Y.getValue());
            PageModel<BpUserMessage> pageData = messageService.findByPage(message, page);
            List<BpUserMessage> userMessageList = pageData.getData();
            for (BpUserMessage userMessage : userMessageList) {
                String uId = userMessage.getCommentsUserId();
                BpUser u = userService.getById(uId);
                UserMessageVO userMessageVo = new UserMessageVO();
                userMessageVo.setId(userMessage.getId());
                userMessageVo.setUserId(userMessage.getUserId());
                userMessageVo.setType(userMessage.getType());
                userMessageVo.setPostId(userMessage.getPostId());
                userMessageVo.setCommentsUserId(uId);
                userMessageVo.setCommentsUserNick(u.getNickName() == null ? "" : u.getNickName());
                userMessageVo.setCommentsUserPhoto(u.getUserPhoto() == null ? "" : u.getUserPhoto());
                userMessageVo.setContent(userMessage.getContent());
                userMessageVo.setCreateTime(userMessage.getCreateTime());
                userMessageVo.setIsRead(userMessage.getIsRead() == null ? "0" : userMessage.getIsRead());
                dataList.add(userMessageVo);
            }
            PageModel<UserMessageVO> data = new PageModel<>();
            data.setData(dataList);
            data.setDraw(pageData.getDraw());
			data.setLength(pageData.getLength());
			// data.setRecordsFiltered(recordsFiltered);
			data.setRecordsTotal(pageData.getRecordsTotal());
			data.setStart(pageData.getStart());

            json.put("data", data);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 置为已读
     */
    @CrossOrigin
    @RequestMapping("/read")
    public String read(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String messageId = request.getParameter("messageId");
            if (StringUtils.isEmpty(messageId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            BpUserMessage message = new BpUserMessage();
            message.setIsRead(CommonCode.Y.getValue());
            messageService.update(message);

            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 删除消息
     * @param request
     * @return
     */
    @CrossOrigin
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String messageId = request.getParameter("messageId");
            if (StringUtils.isEmpty(messageId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            BpUserMessage message = messageService.getById(messageId);
            message.setSymbol(CommonCode.N.getValue());
            messageService.update(message);

            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }


}
